package com.oocl.servlet.action;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.activemq.Producer;
import com.oocl.activemq.factory.ProducerFactory;
import com.oocl.pojo.Application;
import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.ImageUtil;

@WebServlet("/sec/applyStore.action")
public class ApplyStoreActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager merchantManager=null;
	private Producer producer = null;
	private ObjectMapper mapper = null;
	private final String IMG_STORE_LOCATION = "images"+File.separator;
	private final String O2O_STORE_LOCATION = System.getenv("CATALINA_HOME")
			+File.separator+"o2oFile"+File.separator+IMG_STORE_LOCATION;
	private final Integer IMG_SIZE_LIMIT = 1024*1024;
    public ApplyStoreActionServlet() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
        producer = ProducerFactory.getAppProInstance();
        mapper = new ObjectMapper();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Merchant merchant = (Merchant) session.getAttribute("merchant");
		String errorMsg = "";
		String mId="",mName="",mPwd="",mIdCardImg="",mHeadImg="",mAddr="";
		Integer mStatus=null;
		String mIdCardBase64 = null;
		String mHeadBase64 = null;
		byte[] idCardImgByte = null;
		byte[] headImgByte = null;
		String tempDir = System.getProperty("java.io.tmpdir");
		DiskFileItemFactory factory = new DiskFileItemFactory(100*1024, new File(tempDir));
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			//设置所有上传文件的总大小
//			upload.setSizeMax(1024*1024);
			//设置每个上传文件的大小
			upload.setFileSizeMax(1024*1024);
			upload.setHeaderEncoding("UTF-8");
		} catch (Exception e) {
			errorMsg = "图片大小不能超过1MB";
			showErrorMsg(request,response,errorMsg);		
			e.printStackTrace();
		}
		//初始化
		mId = merchant.getmId();
		mIdCardImg = merchant.getmIdCardImg();
		mHeadImg = merchant.getmHeadImg();
		mName = merchant.getmName();
		mAddr = merchant.getmAddr();
		mStatus = merchant.getmStatus();
		
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String itemString = item.getString("UTF-8");
					switch (item.getFieldName()) {
					case "mAddr":
						if (itemString.equals("")){
							errorMsg = "地址不能为空";
							throw new NullPointerException();
						}
						mAddr = itemString;
					}
				}else {
					switch (item.getFieldName()) {
					case "mIdCardImg":
						if(item.getSize()==0){
							String mIdCardImgPath = O2O_STORE_LOCATION+"idcard"
									+File.separator+mId+".jpg";
							InputStream idCardImgIn = new FileInputStream(new File(mIdCardImgPath));
							ByteArrayOutputStream idCardImgBout = new ByteArrayOutputStream();
							IOUtils.copy(idCardImgIn, idCardImgBout);
							idCardImgByte = idCardImgBout.toByteArray();
							mIdCardBase64 = ImageUtil.imgByteToBase(idCardImgByte);
						}else if (item.getSize()>IMG_SIZE_LIMIT) {
							errorMsg="身份照片不能大于1MB";
							throw new Exception();
						}else {
							byte[] idBuf = new byte[1024];
							InputStream idCardImgIn = item.getInputStream();
							ByteArrayOutputStream idCardImgBout = new ByteArrayOutputStream();
							//图片进数据库路径
							String tempMIdCardImg = IMG_STORE_LOCATION+"idcard"+File.separator+mId+".jpg";
							//图片写进本地机器的路径
							String mIdCardImgPath = O2O_STORE_LOCATION+"idcard"
									+File.separator+mId+".jpg";
							OutputStream idCardImgOut = new FileOutputStream(new File(mIdCardImgPath));
							int idLine = 0;
							while((idLine=idCardImgIn.read(idBuf))!=-1){
								idCardImgOut.write(idBuf, 0, idLine);
								idCardImgBout.write(idBuf, 0, idLine);
							}
							idCardImgByte = idCardImgBout.toByteArray();
							idCardImgIn.close();
							idCardImgOut.close();
							idCardImgBout.close();
							mIdCardImg = tempMIdCardImg;
							mIdCardBase64 = ImageUtil.imgByteToBase(idCardImgByte);
						}
						
						break;
					case "mHeadImg":
						if(item.getSize()==0){
							
							String mHeadImgPath = O2O_STORE_LOCATION+"head"
									+File.separator+mId+".jpg";
							InputStream headImgIn = new FileInputStream(new File(mHeadImgPath));
							ByteArrayOutputStream headImgBout = new ByteArrayOutputStream();
							IOUtils.copy(headImgIn, headImgBout);
							headImgByte = headImgBout.toByteArray();
							mHeadBase64 = ImageUtil.imgByteToBase(headImgByte);
						}else if (item.getSize()>IMG_SIZE_LIMIT) {
							errorMsg="头像照片不能大于1MB";
							throw new Exception();
						}else {
							byte[] headBuf = new byte[1024];
							InputStream headImgIn = item.getInputStream();
							ByteArrayOutputStream headImgBout = new ByteArrayOutputStream();
							String tempMHeadImg = IMG_STORE_LOCATION+"head"+File.separator+mId+".jpg";
							String mHeadImgPath = O2O_STORE_LOCATION+"head"
									+File.separator+mId+".jpg";
							OutputStream headImgOut = new FileOutputStream(new File(mHeadImgPath));
							int headLine = 0;
							while((headLine=headImgIn.read(headBuf))!=-1){
								headImgOut.write(headBuf, 0, headLine);
								headImgBout.write(headBuf, 0, headLine);
							}
							headImgByte = headImgBout.toByteArray();
							headImgIn.close();
							headImgOut.close();
							headImgBout.close();
							mHeadImg = tempMHeadImg;
							
							mHeadBase64 = ImageUtil.imgByteToBase(headImgByte);
						}
						break;
					}
				}
			}
			
			merchant.setmAddr(mAddr);
			merchant.setmHeadImg(mHeadImg);
			merchant.setmIdCardImg(mIdCardImg);
			
			Application application = new Application(mId, mName, mIdCardBase64, mHeadBase64, mAddr, mStatus, null, null);
			Protocol protocol = new Protocol(application);
			String json="";
			try {
				json = mapper.writeValueAsString(protocol);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			producer.sendMsgToJMS(json);
			if (merchantManager.updateMerchant(merchant)==0) {
				errorMsg = "服务器出错";
				throw new Exception();
			}
			session.setAttribute("merchant", merchant);
			request.getRequestDispatcher("home").forward(request, response);
		} catch (NullPointerException e) {
			e.printStackTrace();
			showErrorMsg(request,response,errorMsg);	
		} catch (FileUploadException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
			showErrorMsg(request,response,errorMsg);
		}finally{
			errorMsg="";
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private void showErrorMsg(HttpServletRequest request,HttpServletResponse response,String errorMsg){
		request.setAttribute("errorMsg", errorMsg);
		try {
			request.getRequestDispatcher("/WEB-INF/views/applyStore.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
